package com.admin_system.controller;

import com.admin_system.service.EmailService;
import com.admin_system.service.UserService;
import com.admin_system.service.VerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理忘记密码流程的控制器
 * 包括发送验证码、验证验证码以及重置密码的功能
 */
@RestController
@RequestMapping("/api/forgot-password")
public class ForgotPasswordController {

    private static final Logger logger = LoggerFactory.getLogger(ForgotPasswordController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 发送验证码到用户邮箱
     * @param request 包含邮箱的请求
     * @return 发送结果
     */
    @PostMapping("/send-code")
    public ResponseEntity<?> sendVerificationCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        
        if (email == null || email.isEmpty()) {
            logger.warn("发送验证码请求中邮箱为空");
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "邮箱不能为空"));
        }
        
        logger.info("接收到发送验证码请求，邮箱: {}", email);
        
        // 检查邮箱是否已注册
        boolean emailExists = userService.checkEmailExists(email);
        if (!emailExists) {
            logger.warn("邮箱 {} 未注册", email);
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "该邮箱未注册"));
        }
        
        try {
            // 生成并保存验证码
            String code = verificationCodeService.generateCode(email);
            
            // 发送验证码邮件
            boolean sent = emailService.sendVerificationCode(email, code);
            
            if (sent) {
                logger.info("验证码发送成功，邮箱: {}", email);
                return ResponseEntity.ok(Map.of("success", true, "message", "验证码已发送"));
            } else {
                logger.error("验证码发送失败，邮箱: {}", email);
                return ResponseEntity.internalServerError().body(Map.of("success", false, "message", "验证码发送失败，请稍后重试"));
            }
        } catch (Exception e) {
            logger.error("发送验证码出错", e);
            return ResponseEntity.internalServerError().body(Map.of("success", false, "message", "验证码发送失败: " + e.getMessage()));
        }
    }

    /**
     * 验证用户提交的验证码
     * @param request 包含邮箱和验证码的请求
     * @return 验证结果
     */
    @PostMapping("/verify-code")
    public ResponseEntity<?> verifyCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");
        
        if (email == null || email.isEmpty() || code == null || code.isEmpty()) {
            logger.warn("验证请求中邮箱或验证码为空");
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "邮箱和验证码不能为空"));
        }
        
        logger.info("接收到验证码验证请求，邮箱: {}", email);
        
        try {
            // 验证验证码
            boolean isValid = verificationCodeService.verifyCode(email, code);
            
            if (isValid) {
                logger.info("验证码验证成功，邮箱: {}", email);
                
                // 创建会话令牌，用于后续的密码重置
                String resetToken = verificationCodeService.createResetToken(email);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "验证码验证成功");
                response.put("resetToken", resetToken);
                
                return ResponseEntity.ok(response);
            } else {
                logger.warn("验证码验证失败，邮箱: {}", email);
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "验证码无效或已过期"));
            }
        } catch (Exception e) {
            logger.error("验证码验证出错", e);
            return ResponseEntity.internalServerError().body(Map.of("success", false, "message", "验证码验证失败: " + e.getMessage()));
        }
    }

    /**
     * 重置用户密码
     * @param request 包含邮箱和新密码的请求
     * @return 重置结果
     */
    @PostMapping("/reset")
    public ResponseEntity<?> resetPassword(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String password = request.get("password");
        
        if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
            logger.warn("重置密码请求中邮箱或密码为空");
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "邮箱和新密码不能为空"));
        }
        
        logger.info("接收到重置密码请求，邮箱: {}", email);
        
        try {
            // 检查是否有效的重置请求
            boolean hasValidReset = verificationCodeService.hasValidResetToken(email);
            
            if (!hasValidReset) {
                logger.warn("重置密码失败，无效的重置请求，邮箱: {}", email);
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "无效的重置请求，请先验证邮箱"));
            }
            
            // 检查数据库中是否存在多个相同邮箱的用户
            int emailCount = userService.getUserCountByEmail(email);
            if (emailCount > 1) {
                logger.info("发现 {} 个使用邮箱 {} 的用户，将为所有用户重置密码", emailCount, email);
            }
            
            // 重置密码
            boolean reset = userService.resetPasswordByEmail(email, password);
            
            if (reset) {
                logger.info("密码重置成功，邮箱: {}", email);
                
                // 清除重置令牌
                verificationCodeService.clearResetToken(email);
                
                return ResponseEntity.ok(Map.of("success", true, "message", "密码重置成功"));
            } else {
                logger.error("密码重置失败，邮箱: {}", email);
                return ResponseEntity.internalServerError().body(Map.of("success", false, "message", "密码重置失败，请稍后重试"));
            }
        } catch (Exception e) {
            logger.error("重置密码出错", e);
            
            // 提供更具体的错误信息
            String errorMessage = "密码重置失败";
            if (e.getMessage() != null && e.getMessage().contains("TooManyResultsException")) {
                errorMessage = "该邮箱关联了多个账号，请联系管理员处理";
            } else {
                errorMessage += ": " + e.getMessage();
            }
            
            return ResponseEntity.internalServerError().body(Map.of("success", false, "message", errorMessage));
        }
    }
} 